package design;
import java.awt.Dimension;
import java.awt.Font;
import java.io.File;
import javax.swing.JEditorPane;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTree;
import javax.swing.WindowConstants;
import javax.swing.border.EmptyBorder;

/**
 * Simple gui to display an xml tree.
 */
public class XMLViewer extends JFrame {

	private static final long serialVersionUID = 1L;
	private final XMLTree xmlTree;
	private File file;
	private JTree tree;
	private Exception exception;

	private final int windowHeight = 600;
	private final int leftWidth = 703;
	private final int windowWidth = leftWidth;
	private final Font treeFont = new Font("Times New Roman", Font.BOLD, 14);

	/**
	 * Creates a simple gui for viewing xml in a tree.
	 */
	public XMLViewer(String fileName,String title) {

		setTitle(title + " " + fileName);
		setPreferredSize(new Dimension(windowWidth, windowHeight));
		setLocation(100,100);
		setFocusable(true);
		setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);

		xmlTree = new XMLTree();
		
		file = new File(fileName);
		try {
			xmlTree.parseFile(file);
		} catch (Exception e) {
			exception = e;
		}
		tree = xmlTree.getTree();
		display();
	}

	/**
	 * Displays the tree.
	 * 
	 * @param tree
	 *            JTree to display
	 */
	public void display() {
		try {
			JScrollPane treeScrollPane = null;
			
			// Build xml tree view
			if (tree != null) {
				tree.setFont(treeFont);
				treeScrollPane = new JScrollPane(tree);
				treeScrollPane.setPreferredSize(new Dimension(leftWidth,windowHeight));
				treeScrollPane.setBorder(new EmptyBorder(0, 10, 0, 0));
			} else {
				JEditorPane errorMessagePane = new JEditorPane();
				errorMessagePane.setEditable(false);
				errorMessagePane.setContentType("text/plain");
				errorMessagePane
						.setText("Error: unable to build tree from xml:\n"
								+ exception.toString());
				errorMessagePane.setCaretPosition(0);
				treeScrollPane = new JScrollPane(errorMessagePane);
			}
			add("Center" ,treeScrollPane);
			
			pack();
			setVisible(true);
		} catch (Exception e) {
			System.err.println("error when updating xml viewer");
			e.printStackTrace();
		}
	}	
}
